#
# Copyright 2008 Wepoco.  http://www.wepoco.org/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from google.appengine.ext import db
#from google.appengine.api import users, urlfetch
from google.appengine.ext import webapp

from GPXTimeline import GPXTimeline
from datetime import datetime

class Locate(webapp.RequestHandler):
  def get(self):

    #self.response.headers['Content-Type'] = 'application/xml'
    #self.response.headers['Cache-Control'] = 'no-cache'

    track_key = self.request.get('key')
    time = self.request.get('time')
    target_href = "%s/kmllink?key=%s&amp;net=1" % (self.request.host_url,track_key)
    #try:
    if True:
      track = db.get(db.Key(track_key))
      position = GPXTimeline(track.getContent()).getLocation( 
        datetime.strptime(time, '%Y%m%d%H%M%S'))
    #except:
    #  track = None
      pass
    if position:
        self.response.headers['Content-Type']='application/vnd.google-earth.kml+xml'
        #self.response.headers['Content-Disposition']='attachment;filename=%s.kml' % time
        self.response.headers['Cache-Control'] = 'no-cache'
        self.response.out.write("""<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<NetworkLinkControl>
<Update>
<targetHref>%s</targetHref>
<Change><Point targetId="%s">
<coordinates>%f,%f</coordinates>
</Point></Change>
</Update>
</NetworkLinkControl>
</kml>""" % (target_href, time, position.lon, position.lat))

    return

